﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace DarkLight.Model
{
    public class SpaceRegion : SpaceObject, ILocation
    {
        #region Public Members
        public ObservableCollection<Fleet> Fleets
        {
            get
            {
                return _Fleets;
            }
            set
            {
                if (_Fleets != value)
                {
                    RaisePropertyChanging("Fleets");
                    _Fleets = value;
                    RaisePropertyChanged("Fleets");
                }
            }
        }
        private ObservableCollection<Fleet> _Fleets = new ObservableCollection<Fleet>();
        #endregion

        #region ObservableObject Overrides
        protected override void OnPropertyChanging(System.ComponentModel.PropertyChangingEventArgs e)
        {
            if (object.ReferenceEquals(e, null))
                throw new ArgumentNullException("e");

            base.OnPropertyChanging(e);

            if (e.PropertyName == "Fleets")
            {
                if (!object.ReferenceEquals(Fleets, null))
                {
                    foreach (var fleet in Fleets)
                        fleet.ParentOrthonormality = null;
                    Fleets.CollectionChanged -= Fleets_CollectionChanged;
                }
            }
        }

        protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (object.ReferenceEquals(e, null))
                throw new ArgumentNullException("e");

            base.OnPropertyChanged(e);
            
            if (e.PropertyName == "Fleets")
            {
                if (!object.ReferenceEquals(Fleets, null))
                {
                    foreach (var fleet in Fleets)
                        fleet.ParentOrthonormality = this.ParentOrthonormality;
                    Fleets.CollectionChanged += Fleets_CollectionChanged;
                }
            }
        }

        private void Fleets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
                foreach (Fleet fleet in e.NewItems)
                    fleet.ParentOrthonormality = this.ParentOrthonormality;
            else if (e.Action == NotifyCollectionChangedAction.Remove)
                foreach (Fleet fleet in e.OldItems)
                    fleet.ParentOrthonormality = null;
        }
        #endregion

        #region ILocation Implementation
        IList<Fleet> ILocation.Fleets
        {
            get { return Fleets; }
        }
        #endregion
    }
}
